<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <div style="display: flex;">
        <div>
          <el-button
            icon="el-icon-sort"
            type="primary"
            @click="dialogField = true"
            style="margin-right: 10px"
            class="filter-item"
            v-waves
            >
            字段排序</el-button>
        </div>
          <div style="display:inline-block;">
            <div v-for="(item,index) in deviceBarcodeList" :key="index">
              <el-input
                    v-model="item.deviceBarcode"
                    clearable
                    style="margin-right:10px; justify-content:flex-end"
                    :style="{ width: inputWid(item.orderPlanNo) }"
                    class="filter-item"
                    placeholder="批量查询条码"
                    ></el-input>
            </div>
            </div>
            <div style="display: flex;margin-right: 10px">
              <el-button style="margin-right: -5px; height: 30px;" circle type="success" v-waves icon="el-icon-plus" @click="addList"></el-button>
              <el-button style="height: 30px;" type="danger" icon="el-icon-delete" circle @click="deleteList"></el-button>
            </div>
        <!-- <el-input
          @keyup.enter.native="getData"
          clearable
          v-model="listQuery.deviceBarcode"
          style="width: 150px; margin-right: 10px"
          class="filter-item"
          placeholder="请输入条码"
        ></el-input> -->
        <el-input
          @keyup.enter.native="getData"
          clearable
          v-model="listQuery.processOrder"
          style="width: 150px; margin-right: 10px"
          class="filter-item"
          placeholder="请输入工序序号"
        ></el-input>
        <el-input
          @keyup.enter.native="getData"
          clearable
          v-model="listQuery.processName"
          style="width: 150px; margin-right: 10px"
          class="filter-item"
          placeholder="请输入工序名称"
        ></el-input>
        <el-input
          @keyup.enter.native="getData"
          clearable
          v-model="listQuery.po"
          style="width: 150px; margin-right: 10px"
          class="filter-item"
          placeholder="请输入任务令"
        ></el-input>
        <el-input
          @keyup.enter.native="getData"
          clearable
          v-model="listQuery.itemCode"
          style="width: 150px; margin-right: 10px"
          class="filter-item"
          placeholder="请输入客户编码"
        ></el-input>
        <el-select class="filter-item" clearable v-model="listQuery.result" placeholder="状态" style="width: 150px; margin-right: 10px">
          <el-option :value="item.id" :label="item.name" v-for="(item,index) in this.stateList" :key="index"/>
        </el-select>
        <!-- <el-date-picker
          v-model="dateOptions"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          unlink-panels
          placeholder="选择测试时间"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          style="margin-right: 10px"  >
        </el-date-picker> -->
        <div>
          <el-button
            class="filter-item"
            type="primary"
            v-waves
            icon="el-icon-search"
            @click="getData"
            >搜索</el-button>
        </div>
      </div>
    </div>

    <!-- table 表格 -->
    <el-table
      :data="tableInfo"
      element-loading-text="给我一首歌的时间"
      stripe
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="产品条码" prop="deviceBarcode" align="center" />
      <el-table-column label="内部编码" prop="deviceBarcodes" align="center" />
      <el-table-column label="工序序号" prop="processOrder" align="center" />
      <el-table-column label="工序名称" prop="processName" align="center" />
      <el-table-column label="工序编码" prop="processNo" align="center" />
      <el-table-column label="返回结果" prop="result" align="center">
        <template slot-scope="scope">
          {{
            scope.row.result == "True"
              ? "PASS"
              : scope.row.result == "False"
              ? "FAIL"
              : ""
            }}
        </template>
      </el-table-column>
      <el-table-column label="任务令" prop="po" align="center" />
      <el-table-column label="客户编码" prop="itemCode" align="center" />
      <el-table-column label="测试时间" prop="testTime" align="center" />
      <el-table-column label="工单单别" prop="orderType" align="center" />
      <el-table-column label="工单单号" prop="workOrderNo" align="center" />
      <el-table-column label="异常原因" prop="err" align="center" />
    </el-table>
    <el-descriptions size="medium">
      <el-descriptions-item style="width: 300px;" label="合格数量">{{ trueCount }}</el-descriptions-item>
      <el-descriptions-item label="失败数量">{{ falseCount }}</el-descriptions-item>
    </el-descriptions>
    <!-- <div>合格数量:  {{ trueCount }}  失败数量{{ falseCount }}</div> -->

    <el-dialog title="字段排序" :visible.sync="dialogField">
    <el-row :gutter="10">
      <el-form :inline="true" label-width="112px" :model="sortField" ref="sortField" style="width: 100%">
        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="产品条码" :label-width="formLabelWidth" prop="device_barcode">
            <el-select clearable v-model="sortField.device_barcode" placeholder="排序方式" >
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="内部编码" :label-width="formLabelWidth" prop="device_barcodes">
            <el-select clearable v-model="sortField.device_barcodes" placeholder="排序方式" >
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="工序序号" :label-width="formLabelWidth" prop="process_order">
            <el-select clearable v-model="sortField.process_order" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="工序名称" :label-width="formLabelWidth" prop="process_name">
            <el-select clearable v-model="sortField.process_name" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="工序编码" :label-width="formLabelWidth" prop="process_no">
            <el-select clearable v-model="sortField.process_no" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="返回结果" :label-width="formLabelWidth" prop="result">
            <el-select clearable v-model="sortField.result" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          <el-form-item label="任务令" :label-width="formLabelWidth" prop="po">
            <el-select clearable v-model="sortField.po" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="客户编码" :label-width="formLabelWidth" prop="item_code">
            <el-select clearable v-model="sortField.item_code" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="测试时间" :label-width="formLabelWidth" prop="test_time">
            <el-select clearable v-model="sortField.test_time" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="工单单别" :label-width="formLabelWidth" prop="order_type">
            <el-select clearable v-model="sortField.order_type" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="工单单号" :label-width="formLabelWidth" prop="work_order_no">
            <el-select clearable v-model="sortField.work_order_no" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>

          <el-form-item label="异常原因" :label-width="formLabelWidth" prop="err">
            <el-select clearable v-model="sortField.err" placeholder="排序方式">
              <el-option :value="item" :label="item" v-for="(item,index) in this.sortUpDown" :key="index"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
          
        </el-col>
      </el-form>
    </el-row>

    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitSortField">确 定</el-button>
    </div>
    </el-dialog>

    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5, 10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-divider></el-divider>
    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>
  </div>
</template>
  
  <script>
import { hnsHwHmInf } from "@/api/emsPart.js";
export default {
  name: "emstestInquireMX",
  data() {
    return {
      deviceBarcodeList:[{deviceBarcode:''}],
      stateList: [
        { name: "PASS", id: 'True' },
        { name: "FAIL", id: 'False' },
        // { name: "重测", id: 3 },
      ],
      listQuery: {
        page: 1,
        limit: 10,
      },
      total: 0, //返回信息总数
      formLabelWidth: "100px", //弹框内部组件的宽度设定
      dialogFormVisible: false, //变更弹窗显现条件
      modifyform: {
        //ECN变更表单
        ecnChangeId: "", //只显示给用户看，input框为disable
        version: "",
        produceName: "",
        ecnDesc: "",
      },
      pickerOptions: {
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
      dateOptions: this.getNowTime(),
      tableInfo: [], //table表单内容
      userInfo: this.$store.state.user.userInfo,
      sortUpDown: ['升序','降序'],
      dialogField: false,
      sortField: {},
      trueCount: '',
      falseCount: '',
    };
  },
  computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
  methods: {
    getNowTime() {
          let dateTime = +new Date()+8*3600*1000
          const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
              .toISOString()
              .replace('T', ' ')
              .split('.')[0]
              // .substring(0,10) //默认开始时间7天前
          const end = new Date(dateTime)
              .toISOString()
              .replace('T', ' ')
              .split('.')[0]
              // .substring(0,10)//默认结束时间当前时间
          console.log([start, end])
          return [start, end]
        },
    // 点击添加list
    addList(){
            this.deviceBarcodeList.push({deviceBarcode:''})
        },
    // 删除list
    deleteList(){
            if(this.deviceBarcodeList.length > 1){
              this.deviceBarcodeList.pop()
            }
        },
    submitSortField(){
          this.listQuery.sort1 = []
          if(this.sortField.device_barcode){
            let str = 'device_barcode' + ' ' + this.sortShun(this.sortField.device_barcode)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.device_barcodes){
            let str = 'device_barcodes' + ' ' + this.sortShun(this.sortField.device_barcodes)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.process_order){
            let str = 'process_order' + ' ' + this.sortShun(this.sortField.process_order)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.process_name){
            let str = 'process_name' + ' ' + this.sortShun(this.sortField.process_name)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.process_no){
            let str = 'process_no' + ' ' + this.sortShun(this.sortField.process_no)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.result){
            let str = 'result' + ' ' + this.sortShun(this.sortField.result)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.po){
            let str = 'po' + ' ' + this.sortShun(this.sortField.po)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.item_code){
            let str = 'item_code' + ' ' + this.sortShun(this.sortField.item_code)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.test_time){
            let str = 'test_time' + ' ' + this.sortShun(this.sortField.test_time)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.order_type){
            let str = 'order_type' + ' ' + this.sortShun(this.sortField.order_type)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.work_order_no){
            let str = 'work_order_no' + ' ' + this.sortShun(this.sortField.work_order_no)
            this.listQuery.sort1.push(str)
          }
          if(this.sortField.err){
            let str = 'err' + ' ' + this.sortShun(this.sortField.err)
            this.listQuery.sort1.push(str)
          }
          this.dialogField = false
          this.handleFilter()
        },
        cancel(){
          this.dialogField = false
          this.$refs['sortField'].resetFields()
        },
        sortShun(value){
          return value=='升序'?'asc':'desc'
        },
    getData() {
      this.listQuery.page = 1;
      this.handleFilter();
    },
    // 导出excel
    async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          if(this.listQuery.sort1 && this.listQuery.sort1.length) {
            query.sort1 = this.listQuery.sort1.join(',')
          }
          if(this.dateOptions) {
                  if(this.dateOptions.length) {
                      query.strTime = this.dateOptions[0]
                      query.endTime = this.dateOptions[1]
                  }
                }
          if(this.deviceBarcodeList[0].deviceBarcode){
            query.deviceBarcodes = this.deviceBarcodeList.map(item => item.deviceBarcode);  
          }
          query.page = 1
          query.limit = 10000
          let res = await hnsHwHmInf(query)
          const { header, data } = this.transformDat(this.setSort(res.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: 'ems测试明细表', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        transformDat(res) {
          const mapInfo = {
            deviceBarcode: '产品条码',
            deviceBarcodes: '内部编码',
            processOrder:'工序序号',
            processName: '工序名称',
            processNo: '工序编码',
            result: '返回结果',
            po: '任务令',
            itemCode: '客户编码',
            testTime: '测试时间',
            orderType: '工单单别',
            workOrderNo: '工单单号',
            err: '异常原因'
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach(item=>{
            let obj = {
              deviceBarcode: item.deviceBarcode,
              deviceBarcodes: item.deviceBarcodes,
              processOrder: item.processOrder,
              processName: item.processName,
              processNo: item.processNo,
              result: item.result == "True" ? "PASS" : "FAIL",
              po: item.po,
              itemCode: item.itemCode,
              testTime: item.testTime,
              orderType: item.orderType,
              workOrderNo: item.workOrderNo,
              err: item.err,
            }
            arr1.push(obj)
          })
          return arr1
        },
    // 搜索按钮绑定的函数
    // 获取table表单数据与数据总数
    async handleFilter() {
      let query = Object.assign({}, this.listQuery);
      if(this.listQuery.sort1 && this.listQuery.sort1.length) {
        query.sort1 = this.listQuery.sort1.join(',')
      }
      if(this.dateOptions) {
              if(this.dateOptions.length) {
                  query.strTime = this.dateOptions[0]
                  query.endTime = this.dateOptions[1]
              }
            }
      if(this.deviceBarcodeList[0].deviceBarcode){
        query.deviceBarcodes = this.deviceBarcodeList.map(item => item.deviceBarcode);  
      }
      console.log(query)
      let { data } = await hnsHwHmInf(query);
      this.tableInfo = data.list;
      this.trueCount = data.trueCount
      this.falseCount = data.falseCount
      this.total = data.count;
    },
    // table表单下方的页码组件改变每页显示的数据条数
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.handleFilter();
    },
    // table表单下方的页码组件改变页面
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.handleFilter();
    },
  },
  // 进入页面获取table信息
  mounted() {
    this.handleFilter();
  },
};
</script>
  
  <style>
</style>